//
//  TencentViewController.m
//  tcpoctest
//
//  Created by 123456 on 13-8-5.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "TencentViewController.h"
#import <TencentOpenAPI/sdkdef.h>
#import <TencentOpenAPI/TencentOAuthObject.h>
#import "JSONKit.h"
#import "CompleteViewController.h"


#define TENCENT_URL @"https://openmobile.qq.com/oauth2.0"

@interface TencentViewController ()

@end

@implementation TencentViewController
@synthesize navigationTitle = _navigationTitle,tokenArray = _tokenArray;


-(void)initUI{
    [self createTitle];//创建导航条
    self.mtitle.text = _navigationTitle;
    
    UIBarButtonItem * backBtnItem = [self createBarBackButtonItemWithTitle:@"返回" target:self action:@selector(goBackLoginVC)];
    self.navItem.leftBarButtonItem = backBtnItem;
    
    
    tencentWebV = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, WINDOW_HIGTH-44)];
    tencentWebV.delegate = self;
    [self.view addSubview:tencentWebV];
    
    //url请求
    NSString * callbackString = @"tt://qq.peng7.com/qqlogin.php?a=1";
    _encodedValue = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                        (CFStringRef)callbackString,
                                                                        (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                                        NULL,
                                                                        kCFStringEncodingUTF8);
    //    _encodedValue = [callbackString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//URLEncode编码
    
    NSString * urlString = [NSString stringWithFormat:@"%@/m_authorize?response_type=code&client_id=%@&scope=all&redirect_uri=%@&state=1",TENCENT_URL,TENCENT_APPID,_encodedValue];
    NSURL * webURL = [NSURL URLWithString:urlString];
    NSURLRequest * webRequest = [NSURLRequest requestWithURL:webURL];
    [tencentWebV loadRequest:webRequest];
    
    //等待框
    activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityView.center = self.view.center;
    [self.view addSubview:activityView];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    _codeString = [[NSString alloc] init];
    _tokenArray = [[NSMutableArray alloc] init];
    flag = 0;
}





#pragma mark - 返回按钮
-(void)goBackLoginVC{
    [self dismissModalViewControllerAnimated:YES];
}


#pragma mark - webViewDelegate
-(BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType{
    //取到code值
    NSArray * stringArray = [request.URL.absoluteString componentsSeparatedByString:@"&"];
    if ([[[stringArray objectAtIndex:1] substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"code"]) {
        _codeString = [stringArray objectAtIndex:1];
        NSLog(@"urlString = %@\n",_codeString);
        
        //请求token
        NSString * tokenString = [NSString stringWithFormat:@"%@/token?grant_type=authorization_code&client_id=%@&client_secret=%@&%@&redirect_uri=%@",TENCENT_URL,TENCENT_APPID,TENCENT_APPKEY,_codeString,_encodedValue];
        
        [self getTencentData:tokenString];
        
        
    }
    
    return YES;
    
}

//webview开始加载
-(void)webViewDidStartLoad:(UIWebView *)webView{
    [activityView startAnimating];
}

//webview加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [activityView stopAnimating];
}

//webview加载失败
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"error = %@",[error localizedDescription]);
}



#pragma mark - 取token、过期时间和openid
-(void)getTencentData:(NSString *)sender{
    NSURL * tencentURL = [NSURL URLWithString:sender];
    NSURLRequest * tencentRequest = [NSURLRequest requestWithURL:tencentURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    [NSURLConnection connectionWithRequest:tencentRequest delegate:self];
    
}


#pragma mark - NSURLConnectionDataDelegate Methods
//接到服务器响应后调用，调用一次
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    _recieveData = [[NSMutableData alloc] init];//必须用alloc，不能用自动释放池
}

//接收数据时调用，调用多次，直到数据全部接收完
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_recieveData appendData:data];
}
//
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    flag++;
    
    NSString * recieveString = [[NSString alloc] initWithData:_recieveData encoding:NSUTF8StringEncoding];
    NSString * jsonStr = [[NSString alloc] init];
    NSArray  * smallArr = [[NSArray alloc] init];
    
    
    //请求openid
    switch (flag) {
        case 1:
            smallArr = [recieveString componentsSeparatedByString:@"&"];
            [_tokenArray addObjectsFromArray:smallArr];
            NSLog(@"token = %@",_tokenArray);
            if (_tokenArray != nil) {
                NSString * openid = [NSString stringWithFormat:@"%@/me?%@",TENCENT_URL,[smallArr objectAtIndex:0]];
                [self getTencentData:openid];
            }
            break;
            
        case 2:
            jsonStr = [recieveString substringWithRange:NSMakeRange(9, recieveString.length - 12)];
            [self jsonPhrase:jsonStr];
            break;
            
        default:
            break;
    }
    
    
}

//连接错误的时候，调用一次
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"error = %@",[error localizedDescription]);
}



//JSON解析
-(void)jsonPhrase:(NSString *)jsonString{
    NSDictionary * jsonDic = [jsonString objectFromJSONString];
    [_tokenArray addObject:[jsonDic objectForKey:@"openid"]];
    NSLog(@"_tokenArray = %@",self.tokenArray);
    
//    CompleteViewController * completeInfoVC = [[CompleteViewController alloc] init];
//    [self presentModalViewController:completeInfoVC animated:YES];
    [[ViewManager sharedViewManager] showView:VI_COMPLETEINFO
                             withIsRemoveCurV:true
                                withDirection:VD_RIGHT];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
